<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片页 -->
    <el-card>
      <el-alert title="注意，只允许为第三级分类设置参数" type="warning" show-icon>
      </el-alert>
      <!-- 选择商品分类 -->
      <div class="selet_cat">
        <span>选择商品分类:</span>
        <!-- 级联选择器 -->
        <el-cascader v-model="selected" :options="options" :props="selectProps" @change="getDefaultParams">
        </el-cascader>
      </div>
      <!-- tab栏 -->
      <el-tabs v-model="activeName" @tab-click="handleTabChange">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isAbled" @click="showAddDialog">添加动态参数</el-button>

          <!-- 动态的表格 -->
          <el-table :data="manyTableData" stripe border style="width: 100%">
            <!-- expand部分 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(tag,i) in scope.row.attr_vals" :key="i" closable :disable-transitions="false"
                  @close="handleClose(i,scope.row)" style="margin:0px;margin-right:10px;margin-bottom:10px;">
                  {{tag}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)"
                  style="margin:0px;margin-right:10px;margin-bottom:10px;">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button class="el-icon-edit" type="primary" @click="editAttr(scope.row)" size="mini">修改</el-button>
                <el-button class="el-icon-delete" type="danger" @click="deleteAttr(scope.row.attr_id)" size="mini">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isAbled" @click="showAddDialog">添加静态属性</el-button>

          <!-- 静态属性的表格 -->
          <el-table :data="onlyTableData" stripe border style="width: 100%">
            <el-table-column type="expand">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(tag,i) in scope.row.attr_vals" :key="i" closable :disable-transitions="false"
                    @close="handleClose(i,scope.row)" style="margin:0px;margin-right:10px;margin-bottom:10px;">
                    {{tag}}
                  </el-tag>
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                    ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)"
                    style="margin:0px;margin-right:10px;margin-bottom:10px;">+ New Tag</el-button>
                </template>
              </el-table-column>

            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button class="el-icon-edit" type="primary" @click="editAttr(scope.row)">修改</el-button>
                <el-button class="el-icon-delete" type="danger" @click="deleteAttr(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>


    <!-- 添加属性 -->
    <el-dialog :title="activeName=='many'?'添加动态参数':'添加静态属性'" :visible.sync="addDialogVisible" @close="clearForm">
      <el-form :model="addForm" :rules="paramNameRule" ref="addFormRef">
        <el-form-item :label="activeName=='many'?'动态参数名称':'静态属性名称'" label-width="120px" prop="attr_name">
          <el-input v-model="addForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="动态参数选项" label-width="120px" v-if="activeName=='many'" prop="attr_vals">
          <el-input v-model="addForm.attr_vals" type="textarea" autosize></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 编辑属性 -->
    <el-dialog :title="activeName=='many'?'编辑动态参数':'编辑静态属性'" :visible.sync="editDialogVisible" @close="clearEditForm">
      <el-form :model="editForm" :rules="paramNameRule" ref="editFormRef">
        <el-form-item :label="activeName=='many'?'动态参数名称':'静态属性名称'" label-width="120px" prop="attr_name">
          <el-input v-model="editForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="动态参数选项" label-width="120px" v-if="activeName=='many'" prop="attr_vals">
          <el-input v-model="editForm.attr_vals" type="textarea" autosize></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped>
  .el-card {
    margin-top: 30px;
  }

  .selet_cat {
    height: 80px;
    font-size: 20px;
    display: flex;
    align-items: center;

    span {
      margin-right: 30px;
    }
  }

  .el-table {
    margin-top: 20px;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
<script>
  export default {
    data() {
      return {
        selected: [],
        // options: [],
        selectProps: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        options: [],
        activeName: 'many',
        manyTableData: [],
        onlyTableData: [],
        addDialogVisible: false,
        editDialogVisible: false,
        addForm: {},
        editForm: {},
        paramNameRule: {
          attr_name: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],
          attr_vals: [{
            required: true,
            message: '请输入选项',
            trigger: 'blur'
          }]
        },
        editAttrId: 0,
        inputValue: ''
      }
    },
    methods: {
      // 获取所有的1，2，3级分类
      async getClasses() {
        const {
          data: res
        } = await this.$http.get('categories');
        if (res.meta.status == 200) {
          this.options = res.data;
        } else {
          this.$message.error(res.meta.msg);
        }
      },
      handleTabChange() {
        this.getParamsData();
      },
      getDefaultParams() {
        this.getParamsData();
      },
      //获取参数或者属性
      async getParamsData() {
        //   判断是否为3级选项
        if (this.selected.length == 3) {
          const {
            data: response
          } = await this.$http.get(`categories/${this.selected[this.selected.length - 1]}/attributes`, {
            params: {
              sel: this.activeName
            }
          });
          if (response.meta.status == 200) {
            response.data.forEach(element => {
              if (element.attr_vals == '') {
                element.attr_vals = [];

              } else {
                element.inputVisible = false;
                element.inputValue = '';
                element.attr_vals = element.attr_vals.split('，');
                element.attr_vals = element.attr_vals.join(',');
                element.attr_vals = element.attr_vals.split(',');
              }
            });
            if (this.activeName == 'many') {
              this.manyTableData = response.data;

            } else {
              this.onlyTableData = response.data;

            }
          } else {
            // console.log(response.meta.msg);
            this.$message.error(response.meta.msg);
          }
        } else {
          this.manyTableData = [];
          this.onlyTableData = [];
        }
      },
      // 展示添加参数的对话框
      showAddDialog() {
        this.addDialogVisible = true;
      },
      // 清除添加参数的表单
      clearForm() {
        this.$refs.addFormRef.resetFields();
      },
      // 提交添加的参数
      submitAdd() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (valid) {
            const {
              data: res
            } = await this.$http.post(`categories/${this.selected[this.selected.length-1]}/attributes`, {
              attr_sel: this.activeName,
              ...{
                ...this.addForm
              }
            });
            if (res.meta.status == 201) {
              this.$message.success(res.meta.msg);
              this.addDialogVisible = false;
              console.log(res.data);
              this.getParamsData();
            } else {
              this.$message.error(res.meta.msg);
            }


          }
        })
      },
      // 编辑参数
      editAttr(attr) {
        this.editDialogVisible = true;
        attr = {
          ...attr
        };
        attr.attr_vals = attr.attr_vals.join(' ');
        console.log(attr.attr_vals);
        this.editForm = {
          ...attr
        };
        this.editAttrId = attr.attr_id;
      },
      clearEditForm() {
        this.$refs.editFormRef.resetFields();
        this.editForm = {};
      },
      submitEdit() {
        this.$refs.editFormRef.validate(async (valid) => {
          if (valid) {
            this.editDialogVisible = false;
            // console.log(this.editForm);
            const {
              data: res
            } = await this.$http.put(
              `/categories/${this.selected[this.selected.length-1]}/attributes/${this.editAttrId}`, {
                attr_sel: this.activeName,
                ...{
                  ...this.editForm
                }
              });
            if (res.meta.status == 200) {
              this.$message.success(res.meta.msg);
              this.getParamsData();
            } else {
              this.$message.error(res.meta.msg);
            }
          }
        })
      },
      deleteAttr(attr_id) {

        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {
            data: res
          } = await
          this.$http.delete(`/categories/${this.selected[this.selected.length-1]}/attributes/${attr_id}`);
          if (res.meta.status == 200) {
            this.$message.success(res.meta.msg);
            this.getParamsData();
          } else {
            this.$message.error(res.meta.msg);
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleClose(value, row) {
        row.attr_vals.splice(value, 1);
        this.submitTagChange(row);
      },
      async submitTagChange(row) {
        const {
          data: res
        } = await this.$http.put(
          `/categories/${this.selected[this.selected.length-1]}/attributes/${row.attr_id}`, {
            attr_sel: this.activeName,
            attr_name: row.attr_name,
            attr_vals: row.attr_vals.join(',')
          });
        if (res.meta.status == 200) {
          this.$message.success(res.meta.msg);
        } else {
          this.$message.error(res.meta.msg);
        }
      },
      showInput(row) {
        row.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm(row) {
        let inputValue = row.inputValue.trim();
        if (inputValue) {

          row.attr_vals.push(inputValue);
          this.submitTagChange(row);
        }
        row.inputVisible = false;
        row.inputValue = '';
      }
    },
    created() {
      this.getClasses();
    },
    computed: {
      isAbled: function () {
        return this.selected.length == 3 ? false : true;
      }
    }
  }

</script>
